package org.jeecg.modules.mes.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.mes.entity.MesEmployeeWorkType;
import org.jeecg.modules.mes.entity.MesProductionPlan;
import org.jeecg.modules.mes.entity.MesProductionPlanTask;
import org.jeecg.modules.mes.entity.MesTaskParticipant;
import org.jeecg.modules.mes.mapper.MesProductionPlanTaskMapper;
import org.jeecg.modules.mes.service.IMesEmployeeWorkTypeService;
import org.jeecg.modules.mes.service.IMesProductionPlanService;
import org.jeecg.modules.mes.service.IMesProductionPlanTaskService;
import org.jeecg.modules.mes.service.IMesTaskParticipantService;
import org.jeecg.modules.mes.vo.BatchTaskCompleteVO;
import org.jeecg.modules.mes.service.IMesSalaryCalculationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 生产计划工种任务管理
 * @Author: jeecg-boot
 * @Date: 2025-01-21
 * @Version: V1.0
 */
@Service
@Slf4j
public class MesProductionPlanTaskServiceImpl extends ServiceImpl<MesProductionPlanTaskMapper, MesProductionPlanTask> implements IMesProductionPlanTaskService {

    @Autowired
    private IMesProductionPlanService productionPlanService;

    @Autowired
    private IMesEmployeeWorkTypeService employeeWorkTypeService;

    @Autowired
    private ISysBaseAPI sysBaseAPI;

    @Autowired
    private IMesTaskParticipantService taskParticipantService;

    @Autowired
    private IMesSalaryCalculationService salaryCalculationService;

    @Override
    public List<MesProductionPlanTask> getTasksByPlanId(String planId) {
        LambdaQueryWrapper<MesProductionPlanTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MesProductionPlanTask::getPlanId, planId);
        queryWrapper.orderByAsc(MesProductionPlanTask::getSequence);
        return this.list(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitTask(String taskId, String employeeId) {
        MesProductionPlanTask task = this.getById(taskId);
        if (task == null) {
            throw new JeecgBootException("任务不存在");
        }
        
        // 检查员工是否参与了该任务
        MesTaskParticipant participant = taskParticipantService.checkEmployeeParticipation(taskId, employeeId);
        if (participant == null) {
            throw new JeecgBootException("只能操作自己参与的任务");
        }
        
        if (task.getStatus() != 1) {
            throw new JeecgBootException("任务状态不允许提交");
        }
        
        // 更新任务状态为已完成
        task.setStatus(3);
        task.setActualEndDate(new Date());
        task.setCompletedQuantity(task.getTaskQuantity()); // 提交时默认完成全部数量
        this.updateById(task);
        
        // 更新参与者状态为已完成
        participant.setStatus(2); // 已完成
        participant.setEndTime(new Date());
        participant.setCompletedQuantity(task.getTaskQuantity());
        taskParticipantService.updateById(participant);
        
        // 计算薪资记录（只在任务真正完成时添加一次）
        try {
            salaryCalculationService.calculateTaskSalary(participant.getId());
            log.info("任务提交成功，薪资计算完成: taskId={}, employeeId={}, participantId={}", 
                taskId, employeeId, participant.getId());
        } catch (Exception e) {
            log.error("薪资计算失败: taskId={}, employeeId={}, participantId={}", 
                taskId, employeeId, participant.getId(), e);
            // 薪资计算失败不影响任务提交，只记录错误日志
        }
        
        // 更新计划进度
        productionPlanService.updatePlanProgress(task.getPlanId());
        
        log.info("员工{}提交任务{}", employeeId, taskId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void pauseTask(String taskId, String employeeId) {
        MesProductionPlanTask task = this.getById(taskId);
        if (task == null) {
            throw new JeecgBootException("任务不存在");
        }
        
        // 检查员工是否参与了该任务
        MesTaskParticipant participant = taskParticipantService.checkEmployeeParticipation(taskId, employeeId);
        if (participant == null) {
            throw new JeecgBootException("只能操作自己参与的任务");
        }
        
        if (task.getStatus() != 2) {
            throw new JeecgBootException("任务状态不允许暂停");
        }
        
        task.setStatus(4); // 暂停
        this.updateById(task);
        
        log.info("员工{}暂停任务{}", employeeId, taskId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void completeTask(String taskId, String employeeId, Integer completedQuantity, String remark) {
        MesProductionPlanTask task = this.getById(taskId);
        if (task == null) {
            throw new JeecgBootException("任务不存在");
        }
        
        if (task.getStatus() != 2) { 
            throw new JeecgBootException("任务状态不允许完成操作");
        }
        
        // 检查员工是否参与了该任务
        MesTaskParticipant participant = taskParticipantService.checkEmployeeParticipation(taskId, employeeId);
        if (participant == null) {
            throw new JeecgBootException("只能完成自己参与的任务");
        }
        
        task.setStatus(3); // 已完成
        task.setCompletedQuantity(completedQuantity);
        task.setActualEndDate(new Date());
        if (remark != null && !remark.isEmpty()) {
            task.setRemark(task.getRemark() + "\n完成备注：" + remark);
        }
        
        this.updateById(task);
        log.info("员工{}完成任务{}", employeeId, taskId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTaskProgress(String taskId, Integer completedQuantity, String remark) {
        MesProductionPlanTask task = this.getById(taskId);
        if (task == null) {
            throw new JeecgBootException("任务不存在");
        }
        
        if (task.getStatus() != 2) {
            throw new JeecgBootException("只有进行中的任务才能更新进度");
        }
        
        task.setCompletedQuantity(completedQuantity);
        if (remark != null && !remark.isEmpty()) {
            task.setRemark(task.getRemark() + "\n进度更新：" + remark);
        }
        
        this.updateById(task);
        
        log.info("任务{}进度更新，完成数量：{}", taskId, completedQuantity);
    }

    @Override
    public Object getEmployeeTaskStatistics(String employeeId) {
        // 通过参与者表获取员工的任务
        List<MesProductionPlanTask> allTasks = this.getEmployeeTasks(employeeId, null);
        
        Map<String, Object> statistics = new HashMap<>();
        statistics.put("totalTasks", allTasks.size());
        statistics.put("claimedTasks", allTasks.stream().filter(t -> t.getStatus() == 1).count());
        statistics.put("inProgressTasks", allTasks.stream().filter(t -> t.getStatus() == 2).count());
        statistics.put("completedTasks", allTasks.stream().filter(t -> t.getStatus() == 3).count());
        statistics.put("pausedTasks", allTasks.stream().filter(t -> t.getStatus() == 4).count());
        
        // Work hour tracking removed
        
        return statistics;
    }

    @Override
    public List<MesProductionPlanTask> getAvailableTasksForEmployee(String employeeId, String workTypeId) {
        LambdaQueryWrapper<MesProductionPlanTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MesProductionPlanTask::getStatus, 0); // 待领取状态

        if (workTypeId != null && !workTypeId.isEmpty()) {
            queryWrapper.eq(MesProductionPlanTask::getWorkTypeId, workTypeId);
        }

        List<MesProductionPlanTask> allTasks = this.list(queryWrapper);

        // 过滤员工有权限的工种任务
        return allTasks.stream()
                .filter(task -> checkEmployeeWorkTypePermission(employeeId, task.getWorkTypeId()))
                .collect(Collectors.toList());
    }

    public boolean checkEmployeeWorkTypePermission(String employeeId, String workTypeId) {
        LambdaQueryWrapper<MesEmployeeWorkType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MesEmployeeWorkType::getEmployeeId, employeeId);
        queryWrapper.eq(MesEmployeeWorkType::getWorkTypeId, workTypeId);
        queryWrapper.eq(MesEmployeeWorkType::getStatus, 1); // 启用状态

        return employeeWorkTypeService.count(queryWrapper) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void claimTask(String taskId, String employeeId, String remark) {
        MesProductionPlanTask task = this.getById(taskId);
        if (task == null) {
            throw new JeecgBootException("任务不存在");
        }
        
        if (task.getStatus() != 0) {
            throw new JeecgBootException("任务状态不允许领取");
        }
        
        // 验证员工是否具有该工种技能
        LambdaQueryWrapper<MesEmployeeWorkType> employeeWorkTypeWrapper = new LambdaQueryWrapper<>();
        employeeWorkTypeWrapper.eq(MesEmployeeWorkType::getEmployeeId, employeeId);
        employeeWorkTypeWrapper.eq(MesEmployeeWorkType::getWorkTypeId, task.getWorkTypeId());
        employeeWorkTypeWrapper.eq(MesEmployeeWorkType::getStatus, 1);
        
        MesEmployeeWorkType employeeWorkType = employeeWorkTypeService.getOne(employeeWorkTypeWrapper);
        if (employeeWorkType == null) {
            throw new JeecgBootException("员工不具备该工种技能，无法领取任务");
        }
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String employeeName = loginUser.getRealname();
        // 更新任务状态
        task.setStatus(1); // 已领取 待完善
        if (remark != null && !remark.isEmpty()) {
            task.setRemark(task.getRemark() + "\n领取备注：" + remark);
        }
        if(task.getActualStartDate() == null){
            task.setActualStartDate(new Date());
        }
        
        this.updateById(task);

        // 领取成功后添加任务参与者表MesTaskParticipant
        MesTaskParticipant participant = new MesTaskParticipant();
        participant.setTaskId(taskId);
        participant.setEmployeeId(employeeId);
        participant.setEmployeeName(employeeName);
        participant.setClaimedTime(new Date());
        participant.setStatus(0); // 已领取状态
        
        // 保存参与者记录
        taskParticipantService.save(participant);
        
        // 更新任务的当前参与人数
        task.setCurrentParticipants((task.getCurrentParticipants() == null ? 0 : task.getCurrentParticipants()) + 1);
        this.updateById(task);
        
        // 更新计划进度  领取任务代表计划开始执行 修改计划进度为进行中
        productionPlanService.updatePlanProgress(task.getPlanId());
        
        log.info("员工{}({})领取任务{}", employeeName, employeeId, taskId);
    }

    @Override
    public List<MesProductionPlanTask> getEmployeeTasks(String employeeId, Integer status) {
        // 通过参与者表获取员工的任务ID列表
        List<MesTaskParticipant> participants = taskParticipantService.getEmployeeParticipations(employeeId, status);
        if (participants.isEmpty()) {
            return new ArrayList<>();
        }
        
        List<String> taskIds = participants.stream()
                .map(MesTaskParticipant::getTaskId)
                .collect(Collectors.toList());
        
        LambdaQueryWrapper<MesProductionPlanTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(MesProductionPlanTask::getId, taskIds);
        
        if (status != null) {
            queryWrapper.eq(MesProductionPlanTask::getStatus, status);
        }
        
        queryWrapper.orderByAsc(MesProductionPlanTask::getStatus);
        queryWrapper.orderByAsc(MesProductionPlanTask::getSequence);
        queryWrapper.orderByDesc(MesProductionPlanTask::getCreateTime);
        
        List<MesProductionPlanTask> tasks = this.list(queryWrapper);
        
        // 填充计划信息
        for (MesProductionPlanTask task : tasks) {
            try {
                MesProductionPlan plan = productionPlanService.getById(task.getPlanId());
                if (plan != null) {
                    task.setRemark("计划：" + plan.getPlanName() + " | 订单：" + (plan.getOrderNo() != null ? plan.getOrderNo() : "无"));
                }
            } catch (Exception e) {
                log.warn("获取计划信息失败，planId: {}", task.getPlanId(), e);
            }
        }
        
        return tasks;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resumeTask(String taskId, String employeeId) {
        MesProductionPlanTask task = this.getById(taskId);
        if (task == null) {
            throw new JeecgBootException("任务不存在");
        }
        
        // 检查员工是否参与了该任务
        MesTaskParticipant participant = taskParticipantService.checkEmployeeParticipation(taskId, employeeId);
        if (participant == null) {
            throw new JeecgBootException("只能操作自己参与的任务");
        }
        
        if (task.getStatus() != 4) {
            throw new JeecgBootException("任务状态不允许恢复");
        }
        
        task.setStatus(2); // 进行中
        this.updateById(task);
        
        log.info("员工{}恢复任务{}", employeeId, taskId);
    }

    @Override
    public List<MesProductionPlanTask> getEmployeeHistoryTasks(String employeeId, Integer pageNo, Integer pageSize) {
        // 通过参与者表获取员工已完成的任务
        List<MesTaskParticipant> participants = taskParticipantService.getEmployeeParticipations(employeeId, null);
        List<String> taskIds = participants.stream().map(MesTaskParticipant::getTaskId).collect(Collectors.toList());
        
        if (taskIds.isEmpty()) {
            return new ArrayList<>();
        }
        
        LambdaQueryWrapper<MesProductionPlanTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(MesProductionPlanTask::getId, taskIds);
        queryWrapper.eq(MesProductionPlanTask::getStatus, 3); // 已完成状态
        queryWrapper.orderByDesc(MesProductionPlanTask::getActualEndDate);
        queryWrapper.orderByDesc(MesProductionPlanTask::getUpdateTime);
        
        // 分页处理
        if (pageNo != null && pageSize != null && pageNo > 0 && pageSize > 0) {
            int offset = (pageNo - 1) * pageSize;
            queryWrapper.last("LIMIT " + offset + ", " + pageSize);
        }
        
        List<MesProductionPlanTask> tasks = this.list(queryWrapper);
        
        // 填充计划信息
        for (MesProductionPlanTask task : tasks) {
            try {
                MesProductionPlan plan = productionPlanService.getById(task.getPlanId());
                if (plan != null) {
                    task.setRemark("计划：" + plan.getPlanName() + " | 订单：" + (plan.getOrderNo() != null ? plan.getOrderNo() : "无"));
                }
            } catch (Exception e) {
                log.warn("获取计划信息失败，planId: {}", task.getPlanId(), e);
            }
        }
        
        return tasks;
    }

    @Override
    public Object getGroupedTaskData(MesProductionPlanTask queryParam, Integer pageNo, Integer pageSize) {
        try {
            // 1. 构建查询条件
            LambdaQueryWrapper<MesProductionPlanTask> queryWrapper = new LambdaQueryWrapper<>();
            
            if (queryParam.getPlanId() != null && !queryParam.getPlanId().isEmpty()) {
                queryWrapper.eq(MesProductionPlanTask::getPlanId, queryParam.getPlanId());
            }
            if (queryParam.getWorkTypeId() != null && !queryParam.getWorkTypeId().isEmpty()) {
                queryWrapper.eq(MesProductionPlanTask::getWorkTypeId, queryParam.getWorkTypeId());
            }
            if (queryParam.getStatus() != null) {
                queryWrapper.eq(MesProductionPlanTask::getStatus, queryParam.getStatus());
            }
            // 员工筛选现在通过参与者表处理，这里不再需要
            
            // 只显示已下发的生产计划的任务
            queryWrapper.exists("SELECT 1 FROM mes_production_plan p WHERE p.id = mes_production_plan_task.plan_id AND p.status >= 2");
            
            queryWrapper.orderByAsc(MesProductionPlanTask::getSequence);
            queryWrapper.orderByDesc(MesProductionPlanTask::getCreateTime);
            
            // 2. 获取所有任务数据
            List<MesProductionPlanTask> allTasks = this.list(queryWrapper);
            
            // 3. 按生产计划分组
            Map<String, List<MesProductionPlanTask>> planGroups = allTasks.stream()
                .collect(Collectors.groupingBy(MesProductionPlanTask::getPlanId));
            
            // 4. 构建分层数据结构
            List<Map<String, Object>> groupedData = new ArrayList<>();
            
            for (Map.Entry<String, List<MesProductionPlanTask>> planEntry : planGroups.entrySet()) {
                String planId = planEntry.getKey();
                List<MesProductionPlanTask> planTasks = planEntry.getValue();
                
                // 获取生产计划信息
                MesProductionPlan plan = productionPlanService.getById(planId);
                if (plan == null) continue;
                
                // 按工种分组
                Map<String, List<MesProductionPlanTask>> workTypeGroups = planTasks.stream()
                    .collect(Collectors.groupingBy(task -> 
                        task.getWorkTypeId() + "|" + task.getWorkTypeName()));
                
                List<Map<String, Object>> workTypeList = new ArrayList<>();
                for (Map.Entry<String, List<MesProductionPlanTask>> workTypeEntry : workTypeGroups.entrySet()) {
                    String[] workTypeInfo = workTypeEntry.getKey().split("\\|");
                    String workTypeId = workTypeInfo[0];
                    String workTypeName = workTypeInfo.length > 1 ? workTypeInfo[1] : "未知工种";
                    List<MesProductionPlanTask> workTypeTasks = workTypeEntry.getValue();
                    
                    // 计算工种统计信息
                    int totalTasks = workTypeTasks.size();
                    int totalQuantity = workTypeTasks.stream().mapToInt(t -> t.getTaskQuantity() != null ? t.getTaskQuantity() : 0).sum();
                    int completedQuantity = workTypeTasks.stream().mapToInt(t -> t.getCompletedQuantity() != null ? t.getCompletedQuantity() : 0).sum();
                    long completedTasks = workTypeTasks.stream().filter(t -> t.getStatus() != null && t.getStatus() == 3).count();
                    
                    Map<String, Object> workTypeGroup = new HashMap<>();
                    workTypeGroup.put("workTypeId", workTypeId);
                    workTypeGroup.put("workTypeName", workTypeName);
                    workTypeGroup.put("totalTasks", totalTasks);
                    workTypeGroup.put("completedTasks", completedTasks);
                    workTypeGroup.put("totalQuantity", totalQuantity);
                    workTypeGroup.put("completedQuantity", completedQuantity);
                    workTypeGroup.put("progress", totalQuantity > 0 ? (completedQuantity * 100.0 / totalQuantity) : 0);
                    workTypeGroup.put("tasks", workTypeTasks);
                    workTypeGroup.put("expanded", false); // 默认折叠
                    
                    workTypeList.add(workTypeGroup);
                }
                
                // 排序工种列表（按序号）
                workTypeList.sort((a, b) -> {
                    List<MesProductionPlanTask> tasksA = (List<MesProductionPlanTask>) a.get("tasks");
                    List<MesProductionPlanTask> tasksB = (List<MesProductionPlanTask>) b.get("tasks");
                    Integer seqA = tasksA.isEmpty() ? 0 : tasksA.get(0).getSequence();
                    Integer seqB = tasksB.isEmpty() ? 0 : tasksB.get(0).getSequence();
                    return Integer.compare(seqA != null ? seqA : 0, seqB != null ? seqB : 0);
                });
                
                // 计算计划统计信息
                int planTotalTasks = planTasks.size();
                int planTotalQuantity = planTasks.stream().mapToInt(t -> t.getTaskQuantity() != null ? t.getTaskQuantity() : 0).sum();
                int planCompletedQuantity = planTasks.stream().mapToInt(t -> t.getCompletedQuantity() != null ? t.getCompletedQuantity() : 0).sum();
                long planCompletedTasks = planTasks.stream().filter(t -> t.getStatus() != null && t.getStatus() == 3).count();
                
                Map<String, Object> planGroup = new HashMap<>();
                planGroup.put("planId", planId);
                planGroup.put("planName", plan.getPlanName());
                planGroup.put("planNo", plan.getPlanNo());
                planGroup.put("planStatus", plan.getStatus());
                planGroup.put("planStartDate", plan.getPlanStartDate());
                planGroup.put("planEndDate", plan.getPlanEndDate());
                planGroup.put("totalTasks", planTotalTasks);
                planGroup.put("completedTasks", planCompletedTasks);
                planGroup.put("totalQuantity", planTotalQuantity);
                planGroup.put("completedQuantity", planCompletedQuantity);
                planGroup.put("progress", planTotalQuantity > 0 ? (planCompletedQuantity * 100.0 / planTotalQuantity) : 0);
                planGroup.put("workTypes", workTypeList);
                planGroup.put("expanded", false); // 默认折叠
                
                groupedData.add(planGroup);
            }
            
            // 5. 按计划创建时间排序
            groupedData.sort((a, b) -> {
                String planIdA = (String) a.get("planId");
                String planIdB = (String) b.get("planId");
                MesProductionPlan planA = productionPlanService.getById(planIdA);
                MesProductionPlan planB = productionPlanService.getById(planIdB);
                if (planA == null || planB == null) return 0;
                if (planA.getCreateTime() == null || planB.getCreateTime() == null) return 0;
                return planB.getCreateTime().compareTo(planA.getCreateTime()); // 降序
            });
            
            // 6. 分页处理
            int total = groupedData.size();
            int start = (pageNo - 1) * pageSize;
            int end = Math.min(start + pageSize, total);
            
            List<Map<String, Object>> pagedData = new ArrayList<>();
            if (start < total) {
                pagedData = groupedData.subList(start, end);
            }
            
            // 7. 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("records", pagedData);
            result.put("total", total);
            result.put("size", pageSize);
            result.put("current", pageNo);
            result.put("pages", (total + pageSize - 1) / pageSize);
            
            log.info("获取分组任务数据成功，计划数量: {}, 总任务数量: {}", total, allTasks.size());
            return result;
            
        } catch (Exception e) {
            log.error("获取分组任务数据失败", e);
            throw new JeecgBootException("获取分组任务数据失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchCompleteTask(BatchTaskCompleteVO batchCompleteVO) {
        try {
            String employeeId = batchCompleteVO.getEmployeeId();
            List<BatchTaskCompleteVO.TaskCompleteItem> tasks = batchCompleteVO.getTasks();
            String planId = "";
            
            if (tasks == null || tasks.isEmpty()) {
                throw new JeecgBootException("批量完成任务列表不能为空");
            }
            
            // 验证所有任务都属于该员工且状态正确
            for (BatchTaskCompleteVO.TaskCompleteItem taskItem : tasks) {
                MesProductionPlanTask task = this.getById(taskItem.getTaskId());
                if (task == null) {
                    throw new JeecgBootException("任务不存在: " + taskItem.getTaskId());
                }
                planId = task.getPlanId();
                
                // 检查员工是否参与了该任务
                MesTaskParticipant participant = taskParticipantService.checkEmployeeParticipation(taskItem.getTaskId(), employeeId);
                if (participant == null) {
                    throw new JeecgBootException("只能完成自己参与的任务: " + taskItem.getTaskId());
                }
                
                if (task.getStatus() == null || (task.getStatus() != 1 && task.getStatus() != 2 && task.getStatus() != 4)) {
                    throw new JeecgBootException("任务状态不正确，无法完成: " + taskItem.getTaskId());
                }
                
                // 验证完成数量
                if (taskItem.getCompletedQuantity() == null || taskItem.getCompletedQuantity() <= 0) {
                    throw new JeecgBootException("完成数量必须大于0: " + taskItem.getTaskId());
                }
                
                if (taskItem.getCompletedQuantity() > task.getTaskQuantity()) {
                    throw new JeecgBootException("完成数量不能超过任务数量: " + taskItem.getTaskId());
                }
            }
            
            // 批量更新任务状态
            Date now = new Date();
            for (BatchTaskCompleteVO.TaskCompleteItem taskItem : tasks) {
                //更新任务参与表信息  然后更新任务信息
                MesTaskParticipant taskParticipant = taskParticipantService.getOne(new LambdaQueryWrapper<MesTaskParticipant>()
                        .eq(MesTaskParticipant::getTaskId, taskItem.getTaskId())
                        .eq(MesTaskParticipant::getEmployeeId, employeeId)
                );
                MesProductionPlanTask task = this.getById(taskItem.getTaskId());

                taskParticipant.setClaimedQuantity(taskParticipant.getClaimedQuantity() + taskItem.getCompletedQuantity());
                taskParticipant.setCompletedQuantity(taskParticipant.getCompletedQuantity() + taskItem.getCompletedQuantity());
                taskParticipant.setEndTime(now);
                taskParticipantService.updateById(taskParticipant);

                //判断任务下的参与信息完成数量总和是否等于任务的计划数量
                List<MesTaskParticipant> mesTaskParticipantList = taskParticipantService.list(new LambdaQueryWrapper<MesTaskParticipant>()
                        .eq(MesTaskParticipant::getTaskId, taskItem.getTaskId())
                );
                //获取mesTaskParticipantList中所有的完成数量总和
                int completedQuantitySum = mesTaskParticipantList.stream()
                        .map(MesTaskParticipant::getCompletedQuantity)
                        .mapToInt(Integer::intValue)
                        .sum();
                if(completedQuantitySum == task.getTaskQuantity()){
                    taskParticipant.setStatus(2);
                    task.setStatus(3); // 已完成
                    task.setActualEndDate(now);
                }else {
                    taskParticipant.setStatus(1);
                    task.setStatus(2);
                }
                // 更新任务信息
                task.setCompletedQuantity(completedQuantitySum);
                task.setRemark(task.getRemark() + "\n" +taskItem.getRemark());
                task.setUpdateTime(now);
                //更新任务进度
                task.setCompletionRate(BigDecimal.valueOf(completedQuantitySum * 100 / task.getTaskQuantity()));
                
                this.updateById(task);
                taskParticipantService.updateById(taskParticipant);

                // 只有在任务完全完成时才计算薪资，避免重复添加薪资记录
                if (task.getStatus() == 3) { // 任务已完成
                    try {
                        // 使用任务参与者ID计算薪资
                        salaryCalculationService.calculateTaskSalary(taskParticipant.getId());
                        log.info("任务完成，薪资计算成功: taskId={}, employeeId={}, participantId={}, completedQuantity={}", 
                            taskItem.getTaskId(), employeeId, taskParticipant.getId(), taskItem.getCompletedQuantity());
                    } catch (Exception e) {
                        log.error("薪资计算失败: taskId={}, employeeId={}, participantId={}", 
                            taskItem.getTaskId(), employeeId, taskParticipant.getId(), e);
                        // 薪资计算失败不影响任务完成，只记录错误日志
                    }
                }
                
                log.info("批量完成任务: taskId={}, employeeId={}, completedQuantity={}", 
                    taskItem.getTaskId(), employeeId, taskItem.getCompletedQuantity());
            }
            
            log.info("批量完成任务操作成功，共完成{}个任务", tasks.size());

            if(planId != null && !planId.equals("")){
                //若生产计划下的全部任务执行完成，则更新生产计划状态为5已完成
                long count = this.count(new LambdaQueryWrapper<MesProductionPlanTask>()
                        .eq(MesProductionPlanTask::getPlanId, planId)
                        .ne(MesProductionPlanTask::getStatus, 3));
                if(count == 0){
                    productionPlanService.update(new UpdateWrapper<MesProductionPlan>().set("status",5).eq("id",planId));
                }
            }
            
        } catch (Exception e) {
            log.error("批量完成任务失败", e);
            throw new JeecgBootException("批量完成任务失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void withdrawTasks(List<String> taskIds, String employeeId) {
        if (taskIds == null || taskIds.isEmpty()) {
            throw new JeecgBootException("任务ID列表不能为空");
        }
        if (StringUtils.isBlank(employeeId)) {
            throw new JeecgBootException("员工ID不能为空");
        }

        try {
            for (String taskId : taskIds) {
                MesProductionPlanTask task = this.getById(taskId);
                if (task == null) {
                    throw new JeecgBootException("任务不存在: " + taskId);
                }
                
                // 验证只能撤回自己参与的任务
                MesTaskParticipant participant = taskParticipantService.checkEmployeeParticipation(taskId, employeeId);
                if (participant == null) {
                    throw new JeecgBootException("只能撤回自己参与的任务: " + taskId);
                }
                
                // 验证任务状态，只有已领取(1)的任务才能撤回
                if (task.getStatus() != 1) {
                    throw new JeecgBootException("任务状态不允许撤回: " + taskId);
                }
                
                // 重置任务状态为待领取，清除领取相关信息  待完善
                task.setStatus(0);
                
                // 删除参与者记录
                taskParticipantService.removeEmployeeParticipation(taskId, employeeId);
                
                this.updateById(task);
                log.info("员工{}撤回任务{}", employeeId, taskId);
            }
            
            log.info("员工{}成功撤回{}个任务", employeeId, taskIds.size());
        } catch (Exception e) {
            log.error("撤回任务失败", e);
            throw new JeecgBootException("撤回任务失败: " + e.getMessage());
        }
    }
}
